package com.westos.spring.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class MybatisProxy implements InvocationHandler{
	
	private SqlSessionFactory sqlSessionFactory;
	private Class<?> targetclass;
	
	public MybatisProxy(SqlSessionFactory sqlSessionFactory,Class<?> targetclass) {
		this.sqlSessionFactory=sqlSessionFactory;
		this.targetclass=targetclass;
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		
		Object result=null;
		SqlSession sqlSession=null;
		try {
			sqlSession=sqlSessionFactory.openSession();
			Object realObj=sqlSession.getMapper(targetclass);
			result=method.invoke(realObj, args);
		} catch (Exception e) {
			sqlSession.close();
		} finally{
			sqlSession.close();
		}
		
		return result;
	}
	
	
}
